package mac5855.app.dao;

import java.util.List;

import javax.persistence.EntityManager;

import mac5855.app.models.Denuncia;

public class JpaDenunciaDAO implements DenunciaDAO {

	@Override
	public void create(Denuncia newInstance) {

		EntityManager em;
		em = JpaDAOFactory.createConnection();
		em.getTransaction().begin();
		em.persist(newInstance);
		em.getTransaction().commit();
		JpaDAOFactory.releaseConnection(em);
	}

	@Override
	public void delete(Integer id) {
		// TODO Auto-generated method stub

	}

	@Override
	public Denuncia find(Denuncia object) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Denuncia[] findAll() {
		EntityManager em;
		em = JpaDAOFactory.createConnection();
		em.getTransaction().begin();
		List<Denuncia> denuncias = em.createQuery("select p from Denuncia p").getResultList();
		em.getTransaction().commit();
		JpaDAOFactory.releaseConnection(em);

		return (Denuncia[]) denuncias.toArray(new Denuncia[denuncias.size()]);

	}

	@Override
	public void update(Denuncia transientObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public Denuncia findById(Integer id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int findNumDenunciasPergunta(Integer pergunta_id) {

		EntityManager em;
		em = JpaDAOFactory.createConnection();
		em.getTransaction().begin();

		List<Denuncia> denuncias = em.createQuery("select count(*) from denuncias where pergunta_id = ?").setParameter(
				1, pergunta_id).getResultList();

		em.getTransaction().commit();
		JpaDAOFactory.releaseConnection(em);

		return denuncias.size();
	}

	public int findNumDenunciasResposta(Integer resposta_id) {

		EntityManager em;
		em = JpaDAOFactory.createConnection();
		em.getTransaction().begin();

		List<Denuncia> denuncias = em.createQuery("select count(*) from denuncias where resposta_id = ?").setParameter(
				1, resposta_id).getResultList();

		em.getTransaction().commit();
		JpaDAOFactory.releaseConnection(em);

		return denuncias.size();
	}

}
